<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>考评管理</a-breadcrumb-item>
      <a-breadcrumb-item>日常考评</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row>
      <a-col :span="20">
        考评月份：
        <!-- <a-range-picker
          style="width: 330px"
          v-model="creationDateRange"
          :placeholder="['开始日期', '结束日期']"
          valueFormat="YYYY-MM"
          :show-time="{
            hideDisabledOptions: true, 
          }"
          format="YYYY-MM"
          @change="changeDate"
        /> -->
        <!-- <a-date-picker v-model:value="queryForm.kpMonth" picker="year" format="YYYY-MM"/> -->
        <a-date-picker
          v-model:value="queryForm.kpMonth"
          mode="month"
          format="YYYY-MM"      
          :open="monthPickerVisible"           
          placeholder="选择月份"
          @panelChange="handlePanelChange" 
          @focus="() => (monthPickerVisible = true)"
        />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="search()"> 搜索 </a-button>&emsp;&nbsp;
        <a-button @click="reset()">重置</a-button>
      </a-col>
    </a-row>
    <a-spin :spinning="loading">
      <a-row>
        <a-col :span="24">
          <a-table
            :columns="columns"
            :pagination="false"
            :data-source="tableData"
          >
            <span slot="action" slot-scope="text, record">
              <!-- <a class="blue"
                 @click="detailFn(text,record)">查看</a>
              <a-divider type="vertical"/> -->
              <a
                v-hasPermi="['rckp:addRate']"
                class="blue"
                @click="dialogVisible=true,handleOperation('AddScore', record)"
                >加分</a
              >
              <a-divider type="vertical" />
              <a
                v-hasPermi="['rckp:redaceRate']"
                class="blue"
                @click="dialogVisible=true,handleOperation('IncreaseScore', record)"
                >减分</a
              >
              <a-divider type="vertical"/>
              <a class="blue" @click="dialogVisibleScore = true,showAddScore(text.id)">评分记录</a>
              <a-divider type="vertical" />
              <a
                v-hasPermi="['rckp:del']"
                class="red"
                @click="delFn(text, record)"
                >删除</a
              >
            </span>
          </a-table>
          <div class="page_box">
            <a-pagination
              v-model="queryForm.offset"
              :page-size-options="['20', '30', '40', '50']"
              :total="total"
              show-size-changer
              :page-size="queryForm.current"
              @showSizeChange="onShowSizeChange"
              @change="pageChange"
              :show-total="(total) => `共 ${total} 条`"
            ></a-pagination>
          </div>
        </a-col>
      </a-row>
    </a-spin>
    <a-modal
      :title="jiafenStatus === 'AddScore' ? '加分' : '减分'"
      :visible="dialogVisible"
      cancel-text="取消"
      ok-text="确认"
      width="38%"
      @cancel="dialogVisible = false"
      @ok="handleSubmit"
    >
      <a-form :form="form" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
        <a-form-item :label="jiafenStatus === 'AddScore' ? '加分原因' : '减分原因'">
          <a-textarea
            v-decorator="[
              'kpDesc',
              { rules: [{ required: true, message: '必填项' }] },
            ]"
            :rows="4"
            :placeholder="jiafenStatus === 'AddScore' ? '请填写加分原因' : '请填写减分原因'"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="考核工作描述">
          <a-textarea
            v-decorator="[
              'kpWorkDesc',
              { rules: [{ required: true, message: '必填项' }] },
            ]"
            :rows="4"
            placeholder="考核工作描述"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
     <a-modal
      title="加分记录"
      :visible="dialogVisibleScore"
      cancel-text="关闭"
      width="50%"
      @cancel="dialogVisibleScore = false,tableData3=[]"
      @ok="dialogVisibleScore = false,tableData3=[]"
    >
      <a-spin :spinning="loading3">
        <a-table
          :columns="columns3"
          :pagination="false"
          :data-source="tableData3"
        >
        </a-table>
        <div class="page_box">
          <a-pagination
            v-model="queryForm3.offset"
            :page-size-options="['20', '30', '40', '50']"
            :total="total3"
            show-size-changer
            :page-size="queryForm3.current"
            @showSizeChange="onShowSizeChange3"
            @change="pageChange3"
            :show-total="(total3) => `共 ${total3} 条`"
          ></a-pagination>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>
<script>
import { Modal } from "ant-design-vue";
import dayjs from "dayjs";
// import moment from "moment";
export default {
  data() {
    return {
      dialogVisibleScore: false,
      monthPickerVisible: false,
      months: "month",
      tableData: [],
      tableData3:[],//加分记录列表
      columns: [
        {
          title: "考评部门",
          dataIndex: "deptName",
          key: "deptName",
        },
        {
          title: "考评岗位",
          dataIndex: "postName",
          key: "postName",
        },
        {
          title: "考评人员",
          dataIndex: "userName",
          key: "userName",
        },
        {
          title: "当前考评分数",
          dataIndex: "kpSocre",
          key: "kpSocre",
        },
        {
          title: "考评月度",
          dataIndex: "kpMonth",
          key: "kpMonth",
        },
        
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
          fixed: "right",
        },
      ],
      columns3: [
        {
          title: "评分类型",
          dataIndex: "kpType",
          key: "kpType",
          customRender: (text, record, index) => {
              console.log(text);
              return text == 0
                ? "减分"
                : text == 1
                ? "加分"
                : "其他";
            },
        },
        {
          title: "评分领导",
          dataIndex: "kpUserName",
          key: "kpUserName",
        },
        {
          title: "考评描述",
          dataIndex: "kpDesc",
          key: "kpDesc",
        },
        {
          title: "考核工作描述",
          dataIndex: "kpWorkDesc",
          key: "kpWorkDesc",
        },
      ],
      loading: true,
      loading3:false,
      queryForm: {
        current: 20,
        offset: 1,
        kpMonth: null,
      },
      queryForm3: {
        current: 20,
        offset: 1,
        dykmId:0
      },
      total: 0,
      total3: 0,
      menuList: [
        { label: "全部", value: null },
        { label: "遗产保护", value: "HERITAGE_PROTECTION" },
        { label: "经营准入", value: "OPERATION_ACCESS" },
        { label: "保护建设", value: "CONSERVATION_DEVELOPMENT" },
        { label: "执法检查", value: "LAW_ENFORCEMENT_INSPECTION" },
        { label: "数据维护", value: "DATA_MAINTENANCE" },
      ],
      dialogTitle: "",
      dialogVisible: false,
      type: "",
      rowData: {},
      form: this.$form.createForm(this, { name: "coordinated" }),
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
      },
      formTailLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19, offset: 4 },
      },
      creationDateRange: [],
      jiafenStatus:'',
      jiafenData:[]
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
     async showAddScore(id) {
      try {
        // 获取加分列表
        this.loading3 = true;
        // let url = '/government-platform-center/userKpMonthDetail';
        this.queryForm3.dykmId = id;
        const url = "/government-platform-center/userKpMonthDetail?current=" + this.queryForm3.current + "&offset=" + this.queryForm3.offset + "&dykmId=" + this.queryForm3.dykmId
        const res = await this.$axios.get(url, this.queryForm3);
        if (res.data.code !== 0) {
          throw new Error("请求失败: " + res.data.message);
        }

        this.total3 = res.data.total;

        // 使用 Promise.all 并行处理所有用户请求
        this.tableData3 = await Promise.all(
          res.data.data.map(async (item) => ({
            ...item,
            kpUserName: await this.getUser(item.kpUserId),
          }))
        );
        // console.log('----',this.queryForm3)
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("数据加载失败");
      } finally {
        this.loading3 = false;
      }
    },
    // 插入加减分记录
    userKpMonthDetail(data){
      console.log('表单-----',this.form)
      console.log('加减分成功-----',data)
      
      let url = "/government-platform-center/userKpMonthDetail";
      let datainfo = JSON.parse(localStorage.getItem("userInfo"));
      let kp = this.jiafenStatus == "AddScore" ? 1 : -1;
      let kpType = this.jiafenStatus == "AddScore" ? 1 : 0;
      const form = {
        dykmId: data.id,
        kpDesc: data.kpDesc, //考评描述
        kpWorkDesc: data.kpWorkDesc, //考评工作描述
        kpNum: kp,// 变化分数 前端直传-1或1
        kpUserId: datainfo.userId,//评分领导
        kpType:kpType,//评类型 0-减分 1-加分
      };
      this.$axios
        .post(url, form, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        })
        .then((res) => {
        
        });
    },
    // 分页
    onShowSizeChange3(current, pageSize) {
      // console.log(pageSize);
      this.queryForm3.offset = current;
      this.queryForm3.current = pageSize;
      let id = this.queryForm3.dykmId;
      // console.log('this.queryForm3.dykmId',this.queryForm3.dykmId)

      this.showAddScore(id);
    },
    pageChange3(current) {
      let id = this.queryForm3.dykmId;
      this.queryForm3.offset = current;
      // console.log('this.queryForm3.dykmId',this.queryForm3.dykmId)
      this.showAddScore(id);
    },
    // moment,
     // 处理月份选择事件
    handlePanelChange(value, mode) {
      this.queryForm.kpMonth = value.format('YYYY-MM');
      // 2. 关闭弹窗
      this.monthPickerVisible = false;
    },
    // 分页
    onShowSizeChange(current, pageSize) {
      console.log(pageSize);
      this.queryForm.offset = current;
      this.queryForm.current = pageSize;
      this.getList();
    },
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },
    changeDate(val) {
      this.queryForm.startTime = val[0];
      this.queryForm.endTime = val[1];
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (err) {
          return;
        }

        let row = this.jiafenData;
      let type = this.jiafenStatus;

      let url = "/government-platform-center/userKpMonth/edit";
      let kpSocre = row.kpSocre ? Number(row.kpSocre) : 0; //当前分数
      // console.log('kpkpkp',kp)

      let kp = type == "AddScore" ? kpSocre + 1 : kpSocre - 1;
      this.loading = true;

      const form = {
        id: row.id,
        userId: row.userId,
        kpMonth: row.kpMonth,
        kpSocre: kp <= 0 ? 0 : kp,
      };
      this.$axios
        .post(url, form, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        })
        .then((res) => {

          this.loading = false;
          if (res.data.code == 0) {
            this.form.resetFields();
            this.reset();
            this.dialogVisible = false;
            let data = res.data.data;
            this.userKpMonthDetail({...form,...values});
          }
        });

      })
      
    },
    search() {
      this.tableData = [];
      this.queryForm.offset = 1;
      this.getList();
    },
    reset() {
      this.tableData = [];
      this.queryForm.offset = 1;
      this.queryForm.kpMonth = "";
      this.getList();
    },
    getList() {
      this.loading = true;
      const url =
        "/government-platform-center/userKpMonth?current=" +
        this.queryForm.current +
        "&offset=" +
        this.queryForm.offset +
        "&kpMonth=" +
        (this.queryForm.kpMonth ? this.queryForm.kpMonth : ''); 
        this.$axios.get(url, this.queryForm).then((res) => {
          if (res.data.code == 0) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          }
          this.loading = false;
        });
    },
   
    detailFn(text) {
      this.$router.push({
        path: `/RckpDetail`,
        query: { id: text.id },
      });
    },
    delFn(text, record) {
      console.log(text, record);
      const that = this;
      Modal.confirm({
        title: "确认删除",
        content: "您确定要删除这项内容吗？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          const url = `/government-platform-center/userKpMonth?id=${text.id}`;
          that.$axios.delete(url).then((res) => {
            if (res.data.code == 0) {
              that.getList();
              message.success("操作成功");
            }
          });
        },
        onCancel() {
          // 在此处理取消逻辑
          console.log("删除已取消");
        },
      });
    },
    handleOperation(type, row) {
      this.jiafenData = row;
      this.jiafenStatus = type;
      console.log(type, "type");
      
    },
    getUser(id) {
      return this.$axios
        .get("/government-platform-center/user/getUserInfo?userId=" + id)
        .then((res) => {
          return res.data.data.userName;
        })
        .catch((error) => {
          // 建议添加错误处理
          console.error("获取用户失败:", error);
          return "未知用户"; // 返回默认值
        });
    },
  },
};
</script>
<style scoped>
.ant-row {
  border-radius: 5px;
  margin-bottom: 15px;
  background: #fff;
  padding: 20px;
  color: #000;
}

/deep/ .ant-table-thead > tr > th {
  color: #000;
  font-weight: bold;
}

/deep/ .ant-table-tbody > tr > td {
  color: #000;
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}
</style>
